/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.ages.graphics

import javax.media.opengl.GL
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.HashMap
import scala.xml.Node
import scala.xml.XML

class AnimatedSprite(filename:String) extends Sprite(filename,1,1,1){

  val metaFile = getClass.getResource(metaFilename).getFile
  val metaData = XML.loadFile(metaFile)
  val animationMap:HashMap[String,ArrayBuffer[Node]] = animations
  def animations = {
    val animMap = new HashMap[String,ArrayBuffer[Node]]()
    for(animation <- (metaData \\ "model") \\ "img" \\ "animation" )
    {
      val frames = new ArrayBuffer[Node]()
      for(frame <-animation \\ "frame")
      {
        frames+= frame
      }
      animMap += (animation \\ "@name").text -> frames
    }
    animMap
  }

  def metaFilename = {
    val split = filename.split("\\.")
    split(0)+".xml"
  }

  override def toString = {
    "metaData:"+metaData+"\n"
  }

  def drawElement(gl:GL,animation:String,frameNum:Int){
    if(loaded)
    {
      gl.glDisable(GL.GL_LIGHTING)
      val frames = animationMap(animation)
      if(frameNum>=frames.length)
        throw new RuntimeException("Error: Trying to draw frame number:"+(frameNum+1)+", in an animation with only "+frames.length+"frames")
      val spb =  new SpriteBufferManager(gl:GL)
      spb.drawFrame(spriteBuffer,frames(frameNum))
    }
  }
}

